class Solution {
public:
    int nextInt(string& s, int& j) {
        while (s[++j] == ' ');
        int a = s[j++] - '0';
        while (s[j] >= '0' && s[j] <= '9') {
            a = a * 10 + (s[j] - '0');
            ++j;
        }
        --j;
        return a;
    }
    int calculate(string s) {
        vector<int> nums;
        int op, op1, j = -1;
        nums.emplace_back(nextInt(s, j));
        while (j < s.size()) {
            char i = s[j];
            if (i == '*' || i == '/') {
                op1 = nextInt(s, j);
                op = nums.back(); nums.pop_back();
                if (i == '*') nums.emplace_back(op * op1);
                else nums.emplace_back(op / op1);
            }
            else if (i == '+') nums.emplace_back(nextInt(s, j));
            else if (i == '-') nums.emplace_back(-nextInt(s, j));
            ++j;
        }
        return accumulate(nums.begin(), nums.end(), 0);
    }
};
